import React, { Component } from 'react'
import '@css/city/city_navigation.scss'

export default class CityNavigation extends Component{
    constructor(props){
        super(props)
        this.state = {
            letters: []
        }
        this.nav = React.createRef()
    }

    render() {
        return <ul
            className="city-nav"
            ref={this.nav}
        >
            {this.state.letters.map(item=>
                <li 
                    className={`letter-${item}`}
                    ref={(dom)=>this[item] = dom}
                    key={item}
                    onTouchStart={ this.handleNavTouchStart }
                    onTouchMove={ this.handleNavTouchMove }
                    onTouchEnd={ this.handleNavTouchEnd }
                >{item}</li>
            )}
        </ul>
    }
    // 滑动开始
    handleNavTouchStart = (e)=> {
         // 获取swiperOffsetTop
         if(!this.navRealOffsetTop){
            this.navRealOffsetTop = this.props.swiperOffsetTop + this.navOffsetTop;
        }
        // 获取每个导航元素的高度
        if(this.A){
            if(!this.letterHeight){
                this.letterHeight = this.A.clientHeight;
            } 
        }
        let letter = e.target.innerHTML;
        // 通过props函数定义的方式，子组件向父组件传递信息
        this.props.handleSetLetter(letter)
        this.touchStatus = true;
    }
    // 滑动进行中
    handleNavTouchMove = (e)=> {
        e.stopPropagation()
        let nowY = e.nativeEvent.touches[0].clientY;
        if(this.touchStatus){
            if(this.timer){
                clearTimeout(this.timer)
            }
            this.timer = setTimeout(()=>{
                let index = Math.floor((nowY - this.navRealOffsetTop) / this.letterHeight);
                if(index >= 0 && index <= this.state.letters.length){
                    // 通过props函数定义的方式，子组件向父组件传递信息
                    if(this.index !== index) {
                        this.props.handleSetLetter(this.state.letters[index])
                        this.index = index;
                    }
                    
                }
            }, 16)
        }
    }
    // 滑动结束
    handleNavTouchEnd = (e)=> {      
        this.touchStatus = false;
    }
    componentDidMount() {
        this.navOffsetTop = this.nav.current.offsetTop;
    }
    componentWillReceiveProps(nextProps) {
        // 当组件更新props时，取出其中的字母排列
        if(this.state.letters.length === 0){
            let letters = []
            for(let i in nextProps.cities){
                letters.push(i)
            }
            this.setState({
                letters
            })
        }
    }
}